package com.k.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.nio.file.attribute.UserPrincipalNotFoundException;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * @author KK
 */
public class AuthReaml extends AuthorizingRealm{
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        /**
         * 1.user 2.user_role 3.role 4.role_perm 5.perm
         * SELECT
         u.id AS 'uid',
         u.username AS 'uname' ,
         u.password AS 'upwd',
         r.id AS 'rid',
         r.rolename AS 'rname',
         p.id AS 'pid',
         p.permissionName AS 'pname'
         FROM t_user u
         LEFT JOIN t_user_role ur ON ur.userId=u.id
         LEFT JOIN t_role r ON r.id=ur.roleId
         LEFT JOIN t_role_permission rp ON rp.roleId=r.id
         LEFT JOIN t_permission p ON p.id=rp.permissionId
         WHERE  u.username=#{username}
         */
        Set<String> roles = new HashSet<>();
        Set<String> perms = new HashSet<>();

        // 2
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(perms);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        // 1. get user login username password and then validate
        String username = upToken.getUsername();
        char[] password = upToken.getPassword();

        // 2. db
        SysUser user = null;//selectUser(username);
        if(user == null){
            //throw new UserPrincipalNotFoundException();
        }
        validatePassword(user,password.toString());

        //2
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo();
        return info;
    }

    private boolean validatePassword(SysUser user,String password){
        return user.getPassword().equals(encodePassword(password));
    }
    private String encodePassword(String pwd){
        return new Md5Hash(pwd).toHex().toString();
    }

    public void clearCachedAuthorizationInfo(){
        clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }
    public AuthorizationInfo getAuthorizationInfo(){
        return getAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }
    public Collection<String> getAllRoles(){
        return getAuthorizationInfo().getRoles();
    }
    public Collection<String> getAllPerms(){
        return getAuthorizationInfo().getStringPermissions();
    }
}
